package com.huilian.iotbox.data.cmd;

import com.huilian.iotbox.data.constants.IotConstant;
import com.huilian.iotbox.data.dto.DeviceDto;
import com.huilian.iotbox.data.enums.VendingMachineTypeEnum;
import com.huilian.iotbox.data.po.OrderItem;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.utils.IotBoxUtil;
import com.huilian.iotbox.data.vo.DeviceVo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 谢洛涛
 * @date 2023/10/6 10:24
 */
public class VendmachPositiveDataFrameCMD {


    public static void main(String[] args) {
        System.out.println(VendmachPositiveDataFrameCMD.LatticeShipment(RandomStringUtils.random(6, true, true), 1, 1));
        System.out.println(VendmachPositiveDataFrameCMD.LatticeShipment(RandomStringUtils.random(6, true, true), 1, 2));
    }

    /**
     * 出货
     *
     * @param
     * @return
     */
    public static String shipment(String deviceNo, String orderNo, List<OrderItem> orderItemList) {
        StringBuilder shipmentList = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            shipmentList.append(IotBoxUtil.singleInt2Hex(orderItem.getHierarchy()))
                    .append(IotBoxUtil.singleInt2Hex(orderItem.getFreightLane()))
                    .append(IotBoxUtil.hexHighToLow(IotBoxUtil.singleInt2Hex_2(orderItem.getNum(), 2)));
        }
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        StringBuilder dataPrefix = new StringBuilder("01C90E");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append("02");
        dataPrefix.append(IotBoxUtil.convertStringToHex(orderNo));
        dataPrefix.append(IotBoxUtil.singleInt2Hex(orderItemList.size()));
        dataPrefix.append(shipmentList);
        Integer lengthStr = (dataPrefix.length() / 2) + 1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();

    }


    /**
     * 出货
     *
     * @param
     * @return
     */
    public static String LatticeShipment(String orderNo, Integer hierarchy, Integer freightLane) {

        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C90F");
        dataPrefix.append(IotBoxUtil.convertStringToHex(orderNo)).append("0000").append("02");

        dataPrefix.append(IotBoxUtil.singleInt2Hex(IotBoxUtil.convertToTwoDigit(hierarchy, freightLane)))
//            .append("0500")
        ;
        Integer lengthStr = (dataPrefix.length() / 2) + 1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }


    /**
     * 电磁锁不兼容乐瑶瑶的协议，批量出货
     *
     * @param
     * @return
     */
    public static String LatticeShipmentTestNew(String deviceNo, String orderNo, List<OrderItem> orderItemList, String cmd) {
        StringBuilder shipmentList = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            shipmentList.append(IotBoxUtil.singleInt2Hex(orderItem.getHierarchy()))
                    .append(IotBoxUtil.singleInt2Hex(orderItem.getFreightLane()))
                    .append(IotBoxUtil.hexHighToLow(IotBoxUtil.singleInt2Hex_2(orderItem.getNum(), 2)));
        }
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C9FF");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append(cmd);
        dataPrefix.append(IotBoxUtil.convertStringToHex(orderNo));
        dataPrefix.append(IotBoxUtil.singleInt2Hex(orderItemList.size()));
        dataPrefix.append(shipmentList);
        Integer lengthStr = (dataPrefix.length() / 2) + 1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }


    // 电机测试
    public static String motorTesting(String deviceNo, String orderNo, List<OrderItem> orderItemList) {
        StringBuilder shipmentList = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            shipmentList.append(IotBoxUtil.singleInt2Hex(orderItem.getHierarchy()))
                    .append(IotBoxUtil.singleInt2Hex(orderItem.getFreightLane()))
                    .append(IotBoxUtil.hexHighToLow(IotBoxUtil.singleInt2Hex_2(orderItem.getNum(), 2)));
        }
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C90E");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append("04");
        dataPrefix.append(IotBoxUtil.convertStringToHex(orderNo));
        dataPrefix.append(IotBoxUtil.singleInt2Hex(orderItemList.size()));
        dataPrefix.append(shipmentList);
        Integer lengthStr = (dataPrefix.length() / 2) + 1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }


    //     修改设备配置
    public static String updateConfiguration(String deviceNo, DeviceDto deviceDto) {
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C913");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append("02");
        dataPrefix.append("00").append("0000"); // 总通道数量和通道序号暂时默认成0
        // 传 01 02 这些是之前定好的，后续没办法改，所以只能继续这样
        if (VendingMachineTypeEnum.SPRING_MACHINE.getCode().equals(deviceDto.getVendingMachineType())) {
            dataPrefix.append("00");
        } else if (VendingMachineTypeEnum.ELECTROMAGNETIC_LOCK.getCode().equals(deviceDto.getVendingMachineType())) {
            dataPrefix.append("01");
        } else if (VendingMachineTypeEnum.WITHOUT_FEEDBACK_SPECIAL_EDITION_30021.getCode().equals(deviceDto.getVendingMachineType())) {
            dataPrefix.append("02");
        } else if(VendingMachineTypeEnum.LATTIC_MACHINE.getCode().equals(deviceDto.getVendingMachineType())){
            dataPrefix.append("04");
        } else {
            dataPrefix.append("03");
        }
//        if(StringUtils.isEmpty(deviceDto.getFeedback()) || DeviceFeedbackTypeEnum.NOT_DEMAND.getCode().equals(deviceDto.getFeedback())) {
        dataPrefix.append("00");
//        }else if(DeviceFeedbackTypeEnum.WITH_FEEDBACK.getCode().equals(deviceDto.getFeedback())){
//            dataPrefix.append("01");
//        }else if(DeviceFeedbackTypeEnum.WITHOUT_FEEDBACK.getCode().equals(deviceDto.getFeedback())){
//            dataPrefix.append("02");
//        }
        if (StringUtils.isEmpty(deviceDto.getLockTime())) {
            dataPrefix.append("0000");
        } else {
            // 将秒换算成毫秒，然后因为主板已经是每10毫秒执行累加一次的，所以还要除以10才行
            BigDecimal milliseconds = (deviceDto.getLockTime().multiply(BigDecimal.valueOf(1000))).divide(BigDecimal.valueOf(10));
            dataPrefix.append(IotBoxUtil.singleInt2Hex_2(milliseconds.intValue(), 2));
        }

        if (ObjectUtils.isEmpty(deviceDto.getHierarchySequence()) || deviceDto.getHierarchySequence().equals(0)) {
            dataPrefix.append("00");
        } else if (deviceDto.getHierarchySequence().equals(1)) {
            dataPrefix.append("01");
        } else if (deviceDto.getHierarchySequence().equals(2)) {
            dataPrefix.append("02");
        }

        if (ObjectUtils.isEmpty(deviceDto.getFreightLaneSequence()) || deviceDto.getFreightLaneSequence().equals(0)) {
            dataPrefix.append("00");
        } else if (deviceDto.getFreightLaneSequence().equals(1)) {
            dataPrefix.append("01");
        } else if (deviceDto.getFreightLaneSequence().equals(2)) {
            dataPrefix.append("02");
        }

        if (ObjectUtils.isEmpty(deviceDto.getReverseSequence()) || deviceDto.getReverseSequence().equals(0)) {
            dataPrefix.append("00");
        } else if (deviceDto.getReverseSequence().equals(1)) {
            dataPrefix.append("01");
        } else if (deviceDto.getReverseSequence().equals(2)) {
            dataPrefix.append("02");
        }

        if (ObjectUtils.isEmpty(deviceDto.getFeedbackSequence()) || deviceDto.getFeedbackSequence().equals(0)) {
            dataPrefix.append("00");
        } else if (deviceDto.getFeedbackSequence().equals(1)) {
            dataPrefix.append("01");
        } else if (deviceDto.getFeedbackSequence().equals(2)) {
            dataPrefix.append("02");
        }

        if(StringUtils.isEmpty(deviceDto.getDeliveryTime())){
            dataPrefix.append("0000");
        }else{
            Integer deliveryTime = (deviceDto.getDeliveryTime()*1000)/10;
            dataPrefix.append(IotBoxUtil.singleInt2Hex_2(deliveryTime, 2));
        }

        Integer lengthStr = (dataPrefix.length() / 2) + 1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }


    // 查询售货机配置
    public static String getConfiguration (String deviceNo) {
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C913");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append("08");
        Integer lengthStr = (dataPrefix.length()/2)+1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }

    // 查询售货机配置
    public static String getVendingConfiguration (String deviceNo) {
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C913");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append("04");
        Integer lengthStr = (dataPrefix.length()/2)+1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }


    // 设置温度 风扇 灯控配置
    public static String switchConfiguration (String deviceNo, DeviceDto deviceDto) {
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C913");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append("03");
        dataPrefix.append("00");// 光眼
        if(StringUtils.isEmpty(deviceDto.getLightControl())){  // 灯控
            dataPrefix.append("00");
        }else{
            if(deviceDto.getLightControl().equals(true)){
                dataPrefix.append("01");
            }else{
                dataPrefix.append("00");
            }
        }

//        LocalDateTime lampStartupTime = DateTimeUtils.dateChangeLocalDateTime(deviceDto.getLampStartupTime());
//        dataPrefix.append(IotBoxUtil.date2Hex(DateTimeUtils.formatLocalDateTime(lampStartupTime)));
//        LocalDateTime lampStopTime = DateTimeUtils.dateChangeLocalDateTime(deviceDto.getLampStopTime());
//        dataPrefix.append(IotBoxUtil.date2Hex(DateTimeUtils.formatLocalDateTime(lampStopTime)));
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        if(StringUtils.isEmpty(deviceDto.getLampStartupTime())){
            dataPrefix.append("000000");
        }else{
            try {
                Date lampStartupTime = formatter.parse(deviceDto.getLampStartupTime());
                LocalDateTime localDateTime = DateTimeUtils.dateChangeLocalDateTime(lampStartupTime);
                dataPrefix.append(IotBoxUtil.date2Hex(DateTimeUtils.formatLocalDateTime(localDateTime)));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        if(StringUtils.isEmpty(deviceDto.getLampStopTime())){
            dataPrefix.append("000000");
        }else{
            try {
                Date lampStopTime = formatter.parse(deviceDto.getLampStopTime());
                LocalDateTime localDateTime = DateTimeUtils.dateChangeLocalDateTime(lampStopTime);
                dataPrefix.append(IotBoxUtil.date2Hex(DateTimeUtils.formatLocalDateTime(localDateTime)));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        dataPrefix.append(IotBoxUtil.singleInt2Hex(deviceDto.getTemperatureControl()));// 温控
        if(deviceDto.getCompressorStartingTemperature() >= 0){
            dataPrefix.append("00");
        }else {
            dataPrefix.append("01");// 设置温度值符号位
        }
        dataPrefix.append(IotBoxUtil.singleInt2Hex_2(Math.abs(deviceDto.getCompressorStartingTemperature() * 10), 4)); // 温度数

        if(deviceDto.getCompressorStopTemperature() >= 0){
            dataPrefix.append("00");
        }else {
            dataPrefix.append("01");// 设置温度值符号位
        }
        dataPrefix.append(IotBoxUtil.singleInt2Hex_2(Math.abs(deviceDto.getCompressorStopTemperature() * 10), 4));// 温度数

        if(StringUtils.isEmpty(deviceDto.getFanControl())){
            dataPrefix.append("00");
        }else{
            if(deviceDto.getFanControl().equals(true)){
                dataPrefix.append("01");
            }else{
                dataPrefix.append("00");
            }
        }


        Integer lengthStr = (dataPrefix.length()/2)+1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }

    // 发送系统时间给单片机
    public static String setCurrentTime (String deviceNo) {
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C913");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append("09");
        dataPrefix.append(IotBoxUtil.date2Hex(DateTimeUtils.getCurrentTimeStr()));
        Integer lengthStr = (dataPrefix.length()/2)+1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }


    //蓝牙电量设置
    public static String setBatteryNumber (String deviceNo, Integer batteryNumber) {
        StringBuilder stringBuilder = new StringBuilder(IotConstant.CONTENT_PREFIX);
        // 帧长度
        StringBuilder dataPrefix = new StringBuilder("01C913");
        dataPrefix.append(IotBoxUtil.singleString2Hex(deviceNo)).append("05");
        dataPrefix.append(IotBoxUtil.singleInt2Hex(batteryNumber));
        Integer lengthStr = (dataPrefix.length()/2)+1;
        dataPrefix.insert(0, IotBoxUtil.singleInt2Hex(lengthStr));
        stringBuilder
                .append(dataPrefix)
                .append(IotBoxUtil.checkcode_0007(dataPrefix.toString()))
                .append(IotConstant.CONTENT_SUFFIX);
        return stringBuilder.toString().toUpperCase();
    }





}
